import json
from django.views.generic.base import View
from django.views.generic import ListView
from goods.models import Goods
from django.http import HttpResponse, JsonResponse
from django.forms.models import model_to_dict
from django.core import serializers


class GoodsListView01(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()
        # print(all_goods)
        for goods in all_goods:
            json_dict = dict()
            json_dict['name'] = goods.name
            json_dict['category'] = goods.category.name
            json_dict['shop_price'] = goods.shop_price
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')


class GoodsListView02(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()
        # print(all_goods)
        # for goods in all_goods:
        #     json_dict = dict()
        #     json_dict['name'] = goods.name
        #     json_dict['category'] = goods.category.name
        #     json_dict['shop_price'] = goods.shop_price
        #     json_list.append(json_dict)

        for goods in all_goods:
            json_dict = model_to_dict(instance=goods)
            json_list.append(json_dict)

        import json
        return HttpResponse(json.dumps(json_list), content_type='application/json')


class GoodsListView03(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()
        # print(all_goods)
        # for goods in all_goods:
        #     json_dict = dict()
        #     json_dict['name'] = goods.name
        #     json_dict['category'] = goods.category.name
        #     json_dict['shop_price'] = goods.shop_price
        #     json_list.append(json_dict)

        # from django.forms.models import model_to_dict
        # for goods in all_goods:
        #     json_dict = model_to_dict(instance=goods)
        #     json_list.append(json_dict)

        json_data = serializers.serialize('json', all_goods)

        import json
        return HttpResponse(json_data, content_type='application/json')


class GoodsListView04(View):
    def get(self, request):
        """
        通过Django的View获取商品列表页
        :param request:
        :return:
        """
        json_list = list()
        all_goods = Goods.objects.all()

        json_data = serializers.serialize('json', all_goods)  # 序列化

        # return HttpResponse(json_data, content_type='application/json')
        json_data = json.loads(json_data)  # 转换为数组
        return JsonResponse(json_data, safe=False)
